package cms.web.filter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.DelegatingFilterProxy;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SecurityDelegatingFilterProxy extends DelegatingFilterProxy {

    /*
     * (non-Javadoc)
     *
     * @see
     * org.springframework.web.filter.DelegatingFilterProxy#invokeDelegate(javax
     * .servlet.Filter, javax.servlet.ServletRequest,
     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    protected void invokeDelegate(Filter delegate, ServletRequest request,
                                  ServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request instanceof HttpServletRequest
                && response instanceof HttpServletResponse) {
            HttpServletRequest contextHolderRequest = ((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            //request对象是原始的session对象,contextHolderRequest是spring-session封装后的session
            //此处进行对比,如果不相同,则将原始的替换成spring-session封装后的
            if (request != contextHolderRequest) {
                RequestContextHolder.setRequestAttributes(
                        new ServletRequestAttributes(
                                (HttpServletRequest) request,
                                (HttpServletResponse) response), true);
            }

        }
        super.invokeDelegate(delegate, request, response, filterChain);
    }

}
